package org.jivesoftware;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;


import org.jivesoftware.MainWindow.ChannelChangeDialog;
import org.jivesoftware.resource.Res;
import org.jivesoftware.spark.component.Table;
import org.jivesoftware.spark.util.Encryptor;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;


public class ServerSettingDialog extends JDialog {
    
	 private LocalPreferences localPreferences;
	 
	 private JOptionPane optionPane;
	 private GeneralPanel generalPanel;
	 private ProxyPanel proxyPanel;
	 
	 
	 public GeneralPanel getGeneralPanel() {
		return generalPanel;
	}

	public void setGeneralPanel(GeneralPanel generalPanel) {
		this.generalPanel = generalPanel;
	}

	public ServerSettingDialog(){
		    localPreferences = SettingsManager.getLocalPreferences();
	        generalPanel = new GeneralPanel();
	        proxyPanel = new ProxyPanel();
	}
	
	public void showTable(){
		int rownum = generalPanel.getTable().getTableModel().getRowCount();
		for(int i=rownum-1;i>-1;i--){
			generalPanel.getTable().getTableModel().removeRow(i);
		}
		String serverProp = SettingsManager.getLocalPreferences().getServer();
        List<String>  list = new ArrayList<String>();
        if(serverProp!=null){
        	String[] server = serverProp.split("<server>");
			for(int i=0;i<server.length-1;i++){
				String[] array ={server[i],SettingsManager.getLocalPreferences().getKeyValue("addressField"+server[i])};
				generalPanel.getTable().getTableModel().addRow(array);
			}
        }
	}
	public boolean invoke(JFrame owner){
		JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("服务器设置", generalPanel);
        tabbedPane.addTab("代理设置", proxyPanel);
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
     
        Object[] options = {Res.getString("ok"), Res.getString("cancel")};
        optionPane = new JOptionPane(tabbedPane, JOptionPane.PLAIN_MESSAGE,
                JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);

        mainPanel.add(optionPane, BorderLayout.CENTER);

        this.setTitle("设置");
        this.setContentPane(mainPanel);
        this.pack();
        this.setSize(350,350);
        this.setLocationRelativeTo(owner);

        optionPane.addPropertyChangeListener(new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent arg0) {
		        String value = (String)optionPane.getValue();
		        if (Res.getString("cancel").equals(value)) {
		        	ServerSettingDialog.this.setVisible(false);		   
		        }
		        else if (Res.getString("ok").equals(value)) {
		            boolean valid = generalPanel.validate_settings();
		            valid = valid && proxyPanel.validate_settings();
		            if(valid) {
		            	int rownum = generalPanel.getTable().getRowCount();			            	
		            	StringBuilder servername = new StringBuilder();
		            	for(int i=0;i<rownum;i++){		      
		            		servername.append(generalPanel.getTable().getRowObject(i)[0]);
		            		servername.append("<server>");
		            	}
		            	if(generalPanel.getTable().getSelectedRowObject()==null){
		            		servername.append(" ");
		            		SettingsManager.getLocalPreferences().setServer(servername.toString());			            	
		            	}else{
		            		servername.append(generalPanel.getTable().getSelectedRowObject()[0]);
		            		SettingsManager.getLocalPreferences().setServer(servername.toString());
		            	}		            	
		                generalPanel.saveSettings();
		                proxyPanel.saveSettings();
		                SettingsManager.saveSettings();
		                ServerSettingDialog.this.setVisible(false);
		            } else {
		                optionPane.removePropertyChangeListener(this);
		                optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
		                optionPane.addPropertyChangeListener(this);
		            }
		        }
		        else {
		            // Some unknown operation happened
		            optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
		        }
		    }
		});
        
        this.setResizable(false);
        this.setVisible(true);
        this.toFront();
        this.requestFocus();
        this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
        showTable();
        return true;
		
	}
	
	public boolean invoke(final JFrame owner , final JComboBox box){
		JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("服务器设置", generalPanel);
        tabbedPane.addTab("代理设置", proxyPanel);
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
     
        Object[] options = {Res.getString("ok"), Res.getString("cancel")};
        optionPane = new JOptionPane(tabbedPane, JOptionPane.PLAIN_MESSAGE,
                JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);

        mainPanel.add(optionPane, BorderLayout.CENTER);

        this.setTitle("设置");
        this.setContentPane(mainPanel);
        this.pack();
        this.setSize(350,350);
        this.setLocationRelativeTo(owner);
        showTable();
          
        optionPane.addPropertyChangeListener(new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent arg0) {
		        String value = (String)optionPane.getValue();
		        if (Res.getString("cancel").equals(value)) {
		        	ServerSettingDialog.this.setVisible(false);
		        	//ServerSettingDialog.this.dispose();
		        }
		        else if (Res.getString("ok").equals(value)) {
		        	String boxname = box.getSelectedItem().toString();
		            boolean valid = generalPanel.validate_settings();
		            valid = valid && proxyPanel.validate_settings();
		            if(valid) {
		            	int rownum = generalPanel.getTable().getRowCount();
		            	box.removeAllItems();
		            	StringBuilder servername = new StringBuilder();
		            	for(int i=0;i<rownum;i++){
		            		box.addItem(generalPanel.getTable().getRowObject(i)[0]);
		            		servername.append(generalPanel.getTable().getRowObject(i)[0]);
		            		servername.append("<server>");
		            	}
		            	if(generalPanel.getTable().getSelectedRowObject()==null){
		            		servername.append(" ");
		            		SettingsManager.getLocalPreferences().setServer(servername.toString());
			            	box.addItem("-----------------");
		            		box.addItem("管理服务器");
		            		for(int i=0;i<box.getItemCount()-1;i++){
		            			if(boxname.equals(box.getItemAt(i))){
		            				box.setSelectedItem(boxname);
		            				break;
		            			}
		            			box.setSelectedIndex(0);
		            		}
		            		//box.setSelectedIndex(0);
		            	}else{
		            		servername.append(generalPanel.getTable().getSelectedRowObject()[0]);
		            		SettingsManager.getLocalPreferences().setServer(servername.toString());
			            	box.addItem("-----------------");
		            		box.addItem("管理服务器");
		            		box.setSelectedItem(generalPanel.getTable().getSelectedRowObject()[0]);
		            	}		            	
		                generalPanel.saveSettings();
		                proxyPanel.saveSettings();
		                SettingsManager.saveSettings();
		                ServerSettingDialog.this.setVisible(false);
		            } else {
		                optionPane.removePropertyChangeListener(this);
		                optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
		                optionPane.addPropertyChangeListener(this);
		            }
		        }
		        else {
		            // Some unknown operation happened
		            optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
		        }
		    }
		});
        
        addWindowListener(new WindowAdapter() {
        	public void windowClosing(WindowEvent arg0) {
				// TODO Auto-generated method stub
				//box.setSelectedIndex(0);
			}
		});
			
        this.setResizable(false);
        this.setVisible(true);
        this.toFront();
        this.requestFocus();
        this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);

        return true;
		
	}
	private class GeneralPanel extends JPanel{
		
		private ServerTable table ;
		private JButton increButton = new JButton();
		private JButton editButton = new JButton();
		private JButton deleteButton = new JButton();
		
		public GeneralPanel(){
			table = new ServerTable();
			final JScrollPane pane = new JScrollPane(table);
			JPanel jp = new JPanel();
			JPanel jpanel = new JPanel();
			pane.setBackground(Color.white);
	        pane.setForeground(Color.white);
	        this.setBackground(Color.white);
	        this.setForeground(Color.white);
	        pane.getViewport().setBackground(Color.white);
			ResourceUtils.resButton(increButton, "添加");
			ResourceUtils.resButton(editButton, "编辑");
			ResourceUtils.resButton(deleteButton,"删除");
			setLayout(new BorderLayout());
			add(pane,BorderLayout.CENTER);
			add(jpanel,BorderLayout.EAST);
			jp.setLayout(new GridBagLayout());
            jp.add(increButton, 
                    new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, 
                                            GridBagConstraints.WEST, 
                                            GridBagConstraints.NONE, 
                                            new Insets(5, 5, 5, 5), 0, 0));
            jp.add(editButton, 
                    new GridBagConstraints(0, 1, 2, 1, 1.0, 0.0, 
                                            GridBagConstraints.WEST, 
                                            GridBagConstraints.NONE, 
                                            new Insets(5, 5, 5, 5), 0, 0));
            jpanel.setLayout(new BorderLayout());
            jpanel.add(jp,BorderLayout.NORTH);
            jpanel.add(deleteButton,BorderLayout.SOUTH);
            
          //  jp.add(deleteButton, 
          //         new GridBagConstraints(0,2 , 2, 1, 1.0, 0.0, 
           //                                 GridBagConstraints.WEST, 
           //                                 GridBagConstraints.NONE, 
          //                                  new Insets(5, 5, 5, 5), 0, 0));
		
			increButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					ChannelDialog cf = new ChannelDialog(ServerSettingDialog.this,"incre");
					cf.getPortField().setText("5222");
					
				}  
			});
			
			editButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					if (getGeneralPanel().getTable().getSelectedRowObject()!=null) {
						// TODO Auto-generated method stub
						ChannelDialog cf = new ChannelDialog(
								ServerSettingDialog.this,"edit");
						Object[] arg = getTable().getSelectedRowObject();
						if (arg[0].equals("新中大在线服务座席")) {
							cf.getServerField().setText("新中大在线服务座席");
							cf.getAddressField().setText("211.155.232.145");
							cf.getPortField().setText("5222");
							cf.getUserField().setText(
									SettingsManager.getLocalPreferences()
											.getKeyValue("userField" + arg[0]));
							if (SettingsManager.getLocalPreferences()
									.getKeyValue("passwordBox" + arg[0])
									.equals("true")) {
								String password = SettingsManager
										.getLocalPreferences().getKeyValue(
												"passwordField" + arg[0]);
								password = Encryptor.decrypt(password);
								cf.getPasswordField().setText(password);
								cf.getPasswordBox().setSelected(true);
							}
							cf.getServerField().setEditable(false);
							cf.getAddressField().setEditable(false);
							cf.getPortField().setEditable(false);
						} else {
							cf.getServerField()
									.setText(
											SettingsManager
													.getLocalPreferences()
													.getKeyValue(
															"serverField"
																	+ arg[0]));
							cf.getAddressField().setText(
									SettingsManager.getLocalPreferences()
											.getKeyValue(
													"addressField" + arg[0]));
							cf.getPortField().setText(
									SettingsManager.getLocalPreferences()
											.getKeyValue("portField" + arg[0]));
							cf.getUserField().setText(
									SettingsManager.getLocalPreferences()
											.getKeyValue("userField" + arg[0]));
							if (SettingsManager.getLocalPreferences()
									.getKeyValue("passwordBox" + arg[0])
									.equals("true")) {
								cf.getPasswordBox().setSelected(true);
								String password = SettingsManager
										.getLocalPreferences().getKeyValue(
												"passwordField" + arg[0]);
								password = Encryptor.decrypt(password);
								cf.getPasswordField().setText(password);
							} else {
								cf.getPasswordBox().setSelected(false);
							}

						}
					}else{
						JOptionPane.showMessageDialog(GeneralPanel.this,"请选择一行", "消息", 2);
					}
				}
			});
			
			deleteButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					if (getGeneralPanel().getTable().getSelectedRowObject()!=null) {
						// TODO Auto-generated method stub
						int row = getTable().getSelectedRow();	
						if(row==0){
							JOptionPane.showMessageDialog(GeneralPanel.this,"不能删除新中大在线服务座席", "消息", 2);
						}else{
						getTable().getTableModel().removeRow(row);
						}						
					}else{
						JOptionPane.showMessageDialog(GeneralPanel.this,"请选择一行", "消息", 2);
					}
				}
			});
			
		}
		
		 public boolean validate_settings() {
	            boolean valid = true;
	            return valid;
	        }
		 
		 public ServerTable getTable() {
			return table;
		}

		public void setTable(ServerTable table) {
			this.table = table;
		}

		public void saveSettings() {
			 
		  int row =	table.getRowCount();
		  
		 }
	}
    
	private class ProxyPanel extends JPanel {
        private JCheckBox useProxyBox = new JCheckBox();
        private JComboBox protocolBox = new JComboBox();
        private JTextField hostField = new JTextField();
        private JTextField portField = new JTextField();
        private JTextField usernameField = new JTextField();
        private JPasswordField passwordField = new JPasswordField();

        /**
         * Construct UI.
         */
        public ProxyPanel() {
            JLabel protocolLabel = new JLabel();
            JLabel hostLabel = new JLabel();
            JLabel portLabel = new JLabel();
            JLabel usernameLabel = new JLabel();
            JLabel passwordLabel = new JLabel();

            protocolBox.addItem("SOCKS");
            protocolBox.addItem("HTTP");

            // Add ResourceUtils
            ResourceUtils.resButton(useProxyBox, Res.getString("checkbox.use.proxy.server"));
            ResourceUtils.resLabel(protocolLabel, protocolBox, Res.getString("label.protocol"));
            ResourceUtils.resLabel(hostLabel, hostField, Res.getString("label.host"));
            ResourceUtils.resLabel(portLabel, portField, Res.getString("label.port"));
            ResourceUtils.resLabel(usernameLabel, usernameField, Res.getString("label.username"));
            ResourceUtils.resLabel(passwordLabel, passwordField, Res.getString("label.password"));

            setLayout(new GridBagLayout());
            add(useProxyBox, 
                        new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.NONE, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(protocolLabel, 
                        new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.NONE, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(protocolBox, 
                        new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.HORIZONTAL, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(hostLabel, 
                        new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.NONE, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(hostField, 
                        new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.HORIZONTAL, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(portLabel, 
                        new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.NONE, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(portField, 
                        new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.HORIZONTAL, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(usernameLabel, 
                        new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.NONE, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(usernameField, 
                        new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.HORIZONTAL, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(passwordLabel, 
                        new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.NONE, 
                                                new Insets(5, 5, 5, 5), 0, 0));
            add(passwordField, 
                        new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0, 
                                                GridBagConstraints.WEST, 
                                                GridBagConstraints.HORIZONTAL, 
                                                new Insets(5, 5, 5, 5), 0, 0));


            useProxyBox.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    enableFields(useProxyBox.isSelected());
                }
            });

            // Check localSettings
            if (localPreferences.isProxyEnabled()) {
                useProxyBox.setSelected(true);
            }

            enableFields(useProxyBox.isSelected());

            if (ModelUtil.hasLength(localPreferences.getHost())) {
                hostField.setText(localPreferences.getHost());
            }

            if (ModelUtil.hasLength(localPreferences.getPort())) {
                portField.setText(localPreferences.getPort());
            }

            if (ModelUtil.hasLength(localPreferences.getProxyPassword())) {
                passwordField.setText(localPreferences.getProxyPassword());
            }

            if (ModelUtil.hasLength(localPreferences.getProxyUsername())) {
                usernameField.setText(localPreferences.getProxyUsername());
            }

            if (ModelUtil.hasLength(localPreferences.getProtocol())) {
                protocolBox.setSelectedItem(localPreferences.getProtocol());
            }

        }

        /**
         * Enables the fields of the proxy panel.
         *
         * @param enable true if all fields should be enabled, otherwise false.
         */
        private void enableFields(boolean enable) {
            Component[] comps = getComponents();
            for (Component comp1 : comps) {
                if (comp1 instanceof JTextField || comp1 instanceof JComboBox) {
                    JComponent comp = (JComponent) comp1;
                    comp.setEnabled(enable);
                }
            }
        }

        /**
         * Returns true if a proxy is set.
         *
         * @return true if a proxy is set.
         */
        public boolean useProxy() {
            return useProxyBox.isSelected();
        }

        /**
         * Returns the protocol to use for this proxy.
         *
         * @return the protocol.
         */
        public String getProtocol() {
            return (String)protocolBox.getSelectedItem();
        }

        /**
         * Returns the host to use for this proxy.
         *
         * @return the host.
         */
        public String getHost() {
            return hostField.getText();
        }

        /**
         * Returns the port to use with this proxy.
         *
         * @return the port to use.
         */
        public String getPort() {
            return portField.getText();
        }

        /**
         * Returns the username to use with this proxy.
         *
         * @return the username.
         */
        public String getUsername() {
            return usernameField.getText();
        }

        /**
         * Returns the password to use with this proxy.
         *
         * @return the password.
         */
        public String getPassword() {
            return new String(passwordField.getPassword());
        }

        public boolean validate_settings() {
            boolean valid = true;

            if(useProxyBox.isSelected()) {
                try {
                    Integer.valueOf(portField.getText());
                }
                catch (NumberFormatException numberFormatException) {
                    JOptionPane.showMessageDialog(this, Res.getString("message.supply.valid.port"),
                            Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
                    portField.requestFocus();
                    valid = false;
                }
    
                if (!ModelUtil.hasLength(hostField.getText())) {
                    JOptionPane.showMessageDialog(this, Res.getString("message.supply.valid.host"),
                            Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
                    hostField.requestFocus();
                    valid = false;
                }
            }
            return valid;
        }

        /**
         * Persist the proxy settings to local preferences.
         */
        public void saveSettings() {
            localPreferences.setProxyEnabled(useProxyBox.isSelected());
            if (ModelUtil.hasLength(getProtocol())) {
                localPreferences.setProtocol(getProtocol());
            }

            if (ModelUtil.hasLength(getHost())) {
                localPreferences.setHost(getHost());
            }

            if (ModelUtil.hasLength(getPort())) {
                localPreferences.setPort(getPort());
            }

            if (ModelUtil.hasLength(getUsername())) {
                localPreferences.setProxyUsername(getUsername());
            }

            if (ModelUtil.hasLength(getPassword())) {
                localPreferences.setProxyPassword(getPassword());
            }

            if (!localPreferences.isProxyEnabled()) {
                Properties props = System.getProperties();
                props.remove("socksProxyHost");
                props.remove("socksProxyPort");
                props.remove("http.proxyHost");
                props.remove("http.proxyPort");
                props.remove("http.proxySet");
            }
            else {
                String host = localPreferences.getHost();
                String port = localPreferences.getPort();
                String protocol = localPreferences.getProtocol();

                boolean isValid = ModelUtil.hasLength(host) && ModelUtil.hasLength(port);

                if (isValid) {
                    if (protocol.equals("SOCKS")) {
                        System.setProperty("socksProxyHost", host);
                        System.setProperty("socksProxyPort", port);
                    }
                    else {
                        System.setProperty("http.proxySet", "true");

                        // Set https settings
                        System.setProperty("https.proxyHost", host);
                        System.setProperty("https.proxyPort", port);

                        // Set http settings
                        System.setProperty("http.proxyHost", host);
                        System.setProperty("http.proxyPort", port);
                    }
                }
                else {
                    localPreferences.setProxyEnabled(false);
                }
            }
            SettingsManager.saveSettings();
        }
    }
	
	public class ServerTable extends Table{
        public ServerTable() {
            super(new String[]{"名称","地址"});
            getColumnModel().setColumnMargin(0);
            setSelectionBackground(Table.SELECTION_COLOR);
            setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            setRowSelectionAllowed(true);
            String serverProp = SettingsManager.getLocalPreferences().getServer();
            List<String>  list = new ArrayList<String>();
            if(serverProp!=null){
            	String[] server = serverProp.split("<server>");
				for(int i=0;i<server.length-1;i++){
					String[] array ={server[i],SettingsManager.getLocalPreferences().getKeyValue("addressField"+server[i])};
					getTableModel().addRow(array);
				}
            }else{
            	 list.add("新中大在线服务座席");
                 list.add("211.155.232.145");
                 getTableModel().addRow(list.toArray());
                 SettingsManager.getLocalPreferences().setKeyValue("serverField"+"新中大在线服务座席","新中大在线服务座席");
				 SettingsManager.getLocalPreferences().setKeyValue("addressField"+"新中大在线服务座席","211.155.232.145");
				 SettingsManager.getLocalPreferences().setKeyValue("portField"+"新中大在线服务座席", "5222");
            }                 
        }
      
}
	
	public class ChannelDialog extends JDialog{
		private JLabel serverLabel = new JLabel();
		private JTextField serverField = new JTextField();
		private JLabel addressLabel = new JLabel();
		private JTextField addressField = new JTextField();
		private JLabel portLabel = new JLabel();
		private JTextField portField = new JTextField();
		private JLabel userLabel = new JLabel();
		private JTextField userField = new JTextField();
		private JLabel passwordLabel = new JLabel();
		private JPasswordField passwordField = new JPasswordField();
		private JCheckBox passwordBox = new JCheckBox();
		private JButton saveButton = new JButton();
		private JButton cancelButton = new JButton();
		private JPanel jp1 = new JPanel();
		private JPanel jp2 = new JPanel();
		private JPanel jp3 = new JPanel();
		private JPanel jp4 = new JPanel();
		
		public ChannelDialog(JDialog dialog,final String type){
			super(dialog);
			setTitle("频道编辑");
			ResourceUtils.resLabel(serverLabel,"服务器名称:");
			ResourceUtils.resLabel(addressLabel,"地址：");
			ResourceUtils.resLabel(portLabel, "端口:（默认5222）");
			ResourceUtils.resLabel(userLabel, "用户名：");
			ResourceUtils.resLabel(passwordLabel,"密码：");
			ResourceUtils.resButton(passwordBox,"记住密码");
			ResourceUtils.resButton(saveButton, "确认");
			ResourceUtils.resButton(cancelButton,"取消");
            setLayout(new BorderLayout());
            add(jp1,BorderLayout.NORTH);
            add(jp2,BorderLayout.CENTER);
            add(jp3,BorderLayout.SOUTH);
            jp1.setLayout(new BorderLayout());
            jp1.add(serverLabel,BorderLayout.NORTH);
            jp1.add(serverField,BorderLayout.CENTER);
            jp2.setLayout(new GridLayout(4, 2));
            jp2.add(addressLabel);       
            jp2.add(portLabel);
            jp2.add(addressField);
            jp2.add(portField);
            jp2.add(userLabel);
            jp2.add(passwordLabel);
            jp2.add(userField);
            jp2.add(passwordField);
            jp3.setLayout(new BorderLayout());
            jp3.add(passwordBox,BorderLayout.NORTH);
            jp3.add(jp4,BorderLayout.CENTER);
            jp4.setLayout(new FlowLayout());
            jp4.add(saveButton);
            jp4.add(cancelButton);           
            Point point = dialog.getLocation();            
            point.setLocation(point.getX()+50, point.getY()+50);        
            setLocation(point);
           // setLocationRelativeTo(dialog);
			setSize(252,220);
			setResizable(false);
			setVisible(true);
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			
			
			userField.addFocusListener(new FocusListener() {
				public void focusLost(FocusEvent arg0) {				
					if(userField.getText().trim().equals("")){
						if(passwordField.getPassword().length==0){
							passwordField.setEditable(false);
						}else{
							userField.requestFocus();
						}					
					}else{
						passwordField.setEditable(true);
					}
				}
				public void focusGained(FocusEvent arg0) {
							
				}
			});	
			
			passwordField.addFocusListener(new FocusListener() {
				public void focusLost(FocusEvent arg0) {
				     if(passwordField.getPassword().length!=0 && userField.getText().trim().equals("")){
				    	 userField.requestFocus();
				     }
				}
				public void focusGained(FocusEvent arg0) {
				}
			});
			
			saveButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					if(addressField.getText().trim().equals("")){
						JOptionPane.showMessageDialog(ChannelDialog.this,"地址不能为空", "消息", 2);
					}else{
					SettingsManager.getLocalPreferences().setKeyValue("serverField"+serverField.getText(), serverField.getText().trim());
					SettingsManager.getLocalPreferences().setKeyValue("addressField"+serverField.getText(), addressField.getText().trim());
					SettingsManager.getLocalPreferences().setKeyValue("portField"+serverField.getText(), portField.getText().trim());
					SettingsManager.getLocalPreferences().setKeyValue("userField"+serverField.getText(), userField.getText().trim());
					if(passwordBox.isSelected()) {
						SettingsManager.getLocalPreferences().setKeyValue("passwordBox" + serverField.getText(),"true");
						String password = new String(passwordField.getPassword());
						try {
							password = Encryptor.encrypt(password);
							SettingsManager.getLocalPreferences().setKeyValue("passwordField"+serverField.getText(),password);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
 					}else{
 						SettingsManager.getLocalPreferences().setKeyValue("passwordBox" + serverField.getText(),"false");
 					}
					SettingsManager.saveSettings();
					List<String> list = new ArrayList<String>();
					list.add(serverField.getText().trim());
					list.add(addressField.getText().trim());
					if("incre".equals(type)){
						getGeneralPanel().getTable().getTableModel().addRow(list.toArray());
						dispose();
					}else{
						int row = getGeneralPanel().getTable().getSelectedRow();
						getGeneralPanel().getTable().getTableModel().setValueAt(serverField.getText().trim(), row, 0);
						getGeneralPanel().getTable().getTableModel().setValueAt(addressField.getText().trim(),row,1);
						dispose();
						}		
				}
				}
			});
			
			cancelButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					dispose();
				}
			});
		}

		public JTextField getServerField() {
			return serverField;
		}

		public void setServerField(JTextField serverField) {
			this.serverField = serverField;
		}

		public JTextField getAddressField() {
			return addressField;
		}

		public void setAddressField(JTextField addressField) {
			this.addressField = addressField;
		}

		public JTextField getPortField() {
			return portField;
		}

		public void setPortField(JTextField portField) {
			this.portField = portField;
		}

		public JTextField getUserField() {
			return userField;
		}

		public void setUserField(JTextField userField) {
			this.userField = userField;
		}

		public JPasswordField getPasswordField() {
			return passwordField;
		}

		public void setPasswordField(JPasswordField passwordField) {
			this.passwordField = passwordField;
		}

		public JCheckBox getPasswordBox() {
			return passwordBox;
		}

		public void setPasswordBox(JCheckBox passwordBox) {
			this.passwordBox = passwordBox;
		}
		
	}
	
	public static void main(String[] args){
		//ServerSettingDialog a = new ServerSettingDialog();
		//a.invoke();
	}
	
}
